/**
 * Copyright 2010 - YangJiandong(chunquedong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * ChunMap是开源软件。你可以自由复制、传播本项目的下载包文件，但必须保持其完整性。
 * 我们不用对使用中的风险及由此造成的损失承担任何责任。
 * 详细情况请见《ChunMap许可协议》。
 * 
 * 想了解更多有关ChunMap的信息，请访问http://code.google.com/p/chunmap/
 * 
 * 下面此段程序作者YangJianDong(chunquedong)
 * 最后修改时间2010.7.17
 */
package chunmap.app.tools;

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;

import chunmap.model.elem.Envelope;
import chunmap.app.bench.AbstractTool;
import chunmap.app.bench.EventType;

public abstract class RectangleTool extends AbstractTool{
	//private static final Logger Log = new Logger(Logger.Debug,RectangleTool.class.getName());

	private int x = 0;
	private int y = 0;
	private boolean draging = false;
	protected Envelope envelope; 
	private Color color=Color.black;
	
	@Override
	public boolean actionEvent(AWTEvent event, EventType type) {
		if (event instanceof MouseEvent) {
			MouseEvent e = (MouseEvent) event;
			if (MouseEvent.MOUSE_PRESSED == e.getID()) {
				mousePressed(e);
			} else if (MouseEvent.MOUSE_RELEASED == e.getID()) {
				mouseReleased(e);
			} else if (MouseEvent.MOUSE_DRAGGED == e.getID()) {
				mouseDragged(e);
			}
		}
		
		return true;
	}

	public void mouseDragged(MouseEvent e) {
		if (e.isMetaDown()) return;
		
		envelope=new Envelope(x,y,e.getX(),e.getY());
		int minx = (int)envelope.getMinX();
		int miny = (int)envelope.getMinY();
		int width = (int)envelope.getWidth();
		int height = (int)envelope.getHeight();

		Image image=map.getBufferImage();
		Graphics tg=image.getGraphics();
		tg.setColor(color);
		
		tg.drawImage(map.getOriginImage(), 0, 0,null);
		tg.drawRect(minx, miny, width, height);
		
		image.flush();
		map.getGraphics().drawImage(image, 0, 0,map);
	}

	public void mousePressed(MouseEvent e) {
		if (e.isMetaDown())
			return;
		draging = true;
		x = e.getX();
		y = e.getY();
	}

	public void mouseReleased(MouseEvent e) {
		if (draging) {
			if(envelope!=null){
				finished();
			}
			
			//reset
			draging = false;
			x = 0;
			y = 0;
			envelope=null;
		}
	}
	
	public abstract void finished();
}
